﻿using KBZ.Common;
using Microsoft.Win32;
using Panuon.UI.Silver;
using ServiceLibrary.DtoModel.DeskApp;
using ServiceLibrary.Implements;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace fResApp.PartialViews.Business
{
    public partial class UserInfo : WindowX
    {
        sysUserService userService = new sysUserService();
        public UserInfo()
        {
            InitializeComponent();
        }

        private void WindowX_Loaded(object sender, RoutedEventArgs e)
        {
            verifyData();
        }
        /// <summary>
        /// 更换头像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void upHeadImg_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //var rootImagPath = System.IO.Directory.GetCurrentDirectory().Replace(@"\bin\Debug", "") + @"\Resources\icon\upSys.png";
            //var image = new ImageBrush { ImageSource = new BitmapImage(new Uri(rootImagPath)) };
            //txtHeadImg.Content = rootImagPath;
            //uheadImg.Background = image;
            SelImage();
        }
        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var _curObj = MemoryCacheService.Default.GetCache<sysUser>(CacheKey.UTOKETVALUE);
                if (_curObj != null)
                {
                    var _defaultpwd = Md5Crypt.EncryptToMD5("888888");
                    var _pwd = txtPwd.Password.Trim();
                    if (!_defaultpwd.ToLower().Equals(_pwd.ToLower()))
                    {
                        _pwd = Md5Crypt.EncryptToMD5(_pwd);
                    }
                    var _headimg = txtHeadImg.Content != null ? txtHeadImg.Content.ToString() : string.Empty;
                    var uObj = new sysUserDto
                    {
                        HeadImg = _headimg,
                        uGuid = _curObj.uGuid,
                        uName = txtAccount.Text.Trim(),
                        uPwd = _pwd,
                        uEmail = txtEmail.Text.Trim(),
                        RealName = txtStoreName.Text.Trim(),
                        Addr = txtAddr.Text.Trim()
                    };
                    var _res = userService.UpById(uObj).Result;
                    if (_res.statusCode == (int)ApiEnum.Status)
                    {
                        Notice.Show("保存成功！", "提示", 3, MessageBoxIcon.Success);
                        Logger.Default.Info("【" + _curObj.uName + "】在【" + DateTime.Now + "】成功更新用户信息！");
                    }
                    else
                    {
                        Notice.Show("保存失败！", "提示", 3, MessageBoxIcon.Warning);
                        Logger.Default.ProcessError(_res.statusCode, "更新用户信息时，保存失败");
                    }
                }
                else
                {
                    Notice.Show("保存失败！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError((int)ApiEnum.Error, "更新用户信息时，获取当前缓存用户信息失效");
                }
            }
            catch (Exception ex)
            {
                Notice.Show("保存失败！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.Error("更新用户信息异常", ex);
            }
        }
        private bool verifyData()
        {
            bool isVerify = false;
            try
            {
                var _curObj = MemoryCacheService.Default.GetCache<sysUser>(CacheKey.UTOKETVALUE);
                if (_curObj != null)
                {
                    if (!string.IsNullOrEmpty(verifyCode.IsCode(_curObj.uTell, _curObj.ActiveCode)))
                    {
                        var _curSName = string.IsNullOrEmpty(_curObj.RealName) ? ConfigExtensions.Configuration["CusInfo:StoreName"] : _curObj.RealName;
                        txtStoreName.Text = _curSName;
                        if (!string.IsNullOrEmpty(_curObj.HeadImg))
                        {
                            var image = new ImageBrush { ImageSource = new BitmapImage(new Uri(_curObj.HeadImg)) };
                            uheadImg.Background = image;
                        }
                        txtAccount.Text = _curObj.uName;
                        txtPwd.Password = _curObj.uPwd;
                        txtEmail.Text = _curObj.uEmail;
                        txtAddr.Text = _curObj.Addr;
                        isVerify = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("", ex);
            }
            return isVerify;
        }
        private void SelImage()
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "图片文件(.jpg;.bmp;.png;.jpeg)|*.jpg;*.png;*.jpeg;";
                ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";//文件选择的默认路径 
                if (ofd.ShowDialog() == true)
                {
                    string filePath = ofd.FileName;
                    FileInfo fi = new FileInfo(filePath);
                    long _size = fi.Length;//得到文件的字节大小
                    long _maxSize = 2097152; long.TryParse(ConfigExtensions.Configuration["GroupInfo:FileSize"].ToString(), out _maxSize);
                    if (_size <= _maxSize)//在2m之内
                    {
                        var _curObj = MemoryCacheService.Default.GetCache<sysUser>(CacheKey.UTOKETVALUE);
                        if (_curObj != null)
                        {
                            bool isSave = false;
                            ImageBrush imageBrush = new ImageBrush();
                            var rootHeadImagPath = Directory.GetCurrentDirectory().Replace(@"\bin\Debug", "") + @"\Resources\proImg\" + _curObj.uName + ".png";
                            try
                            {
                                var encoder = new PngBitmapEncoder();
                                encoder.Frames.Add(BitmapFrame.Create(ofd.OpenFile()));
                                FileStream fileStream = new FileStream(rootHeadImagPath, FileMode.Create, FileAccess.ReadWrite);
                                encoder.Save(fileStream);
                                fileStream.Close();
                                isSave = true;
                            }
                            catch (Exception _ex)
                            {
                                Logger.Default.Error("保存上传头像图片异常，保存路径【" + rootHeadImagPath + "】", _ex);
                            }
                            if (isSave)
                            {
                                imageBrush = new ImageBrush { ImageSource = new BitmapImage(new Uri(rootHeadImagPath)) };
                            }
                            else
                            {
                                Notice.Show("更换失败！", "提示", 3, MessageBoxIcon.Warning);
                                rootHeadImagPath = Directory.GetCurrentDirectory().Replace(@"\bin\Debug", "") + @"\Resources\icon\upSys.png";
                                imageBrush = new ImageBrush { ImageSource = new BitmapImage(new Uri(rootHeadImagPath)) };
                            }
                            txtHeadImg.Content = rootHeadImagPath;
                            uheadImg.Background = imageBrush;
                        }
                        else
                        {
                            Notice.Show("更换失败！", "提示", 3, MessageBoxIcon.Warning);
                            Logger.Default.ProcessError((int)ApiEnum.Error, "上传头像图片，获取用户登录缓存失效");
                        }
                    }
                    else
                    {
                        Notice.Show("所选图片过大，请选择2M范围内的图片！", "提示", 3, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                Notice.Show("更换失败！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.Error("上传头像图片异常", ex);
            }
        }
    }
}
